import { useEffect, useState, useMemo } from "react"
import { useParams } from "react-router-dom"
import { message, Button, Spin, Space, Row, Col, Modal } from 'antd'
import { queryDetail, modifyOne } from "../../apis/appDefinition"

import DetailHeader from "../../components/DetailHeader"
import ModelerVersionPicker from "../../components/ModelerVersionPicker"
import useModelVersion from "../../hooks/useModelVersion"
import ModelerSetNewVersion from "../../components/ModelerSetNewVersion"
import { UserEditableTagList, GroupEditableTagList } from "../../components/EditableTagList"
import EditableProcessList from "../../components/EditableProcessList"

const ModelerAppDesign = () => {

  const { id: modelId } = useParams()
  const [loading, setLoading] = useState(false)
  const [appDef, setAppDef] = useState({})

  // 使用模型版本钩子
  const {
    versions,
    doQueryVersions,
    setReleaseVersion,
    curVersion,
    curVerionId,
    isReleaseVersion,
    handleChangeVersion
  } = useModelVersion({
    modelId,
    changeVersionAction: (versionItem, releaseVersion) => {
      if (versionItem.version !== releaseVersion) {
        doQueryDetail(versionItem.id)
      } else {
        doQueryDetail()
      }
    }
  })

  const doQueryDetail = async (versionId) => {
    setLoading(true)
    try {
      const data = await queryDetail(modelId, versionId)
      setAppDef(data)

      // 设置当前版本
      if (!versionId) {
        setReleaseVersion(data.version)
      }

    } catch (error) {
      message.error('查询失败')
    }

    setLoading(false)
  }

  const handleSave = async () => {
    Modal.confirm({
      title: '确定要保存？',
      onOk: async () => {
        try {
          await modifyOne(modelId, {
            appDefinition: {
              ...appDef,
              definition: {
                ...appDef.definition,
                usersAccess: userIds.join(','),
                groupsAccess: groupIds.join(',')
              }
            },
            publish: false
          })
          message.success('保存成功！')
        } catch (error) {
          message.error(error.message || '保存失败！')
        }
      }
    })
  }

  const handleChangeAppDef = (key, value) => {
    setAppDef((oldData) => {
      return {
        ...oldData,
        definition: {
          ...oldData.definition,
          [key]: value
        }
      }
    })
  }

  const userIds = useMemo(() => {
    const usersAccess = appDef.definition?.usersAccess || ''
    return usersAccess ? usersAccess.split(',') : []
  }, [appDef])

  const handleChangeUser = (userIds) => {
    handleChangeAppDef('usersAccess', userIds.join(','))
  }

  const groupIds = useMemo(() => {
    const groupsAccess = appDef.definition?.groupsAccess || ''
    return groupsAccess ? groupsAccess.split(',') : []
  }, [appDef])

  const handleChangeGroup = (groupIds) => {
    handleChangeAppDef('groupsAccess', groupIds.join(','))
  }

  const appProcesses = useMemo(() => appDef.definition?.models || [], [appDef])

  const handleChangeProcess = (processes) => {
    handleChangeAppDef('models', processes)
  }

  useEffect(() => {
    if (modelId) {
      doQueryDetail()
    }
  }, [modelId])

  const renderHeadTitle = () => <Space>
    <b style={{ fontSize: 18 }}>{appDef.name}</b>
    <ModelerVersionPicker
      versions={versions}
      value={curVersion}
      onChange={handleChangeVersion}
    ></ModelerVersionPicker>
  </Space>

  const renderHeadBtns = () => <Space>
    {
      !!appDef.name && (
        isReleaseVersion ?
          <Button type="primary" onClick={handleSave}>保存</Button> :
          <ModelerSetNewVersion
            modelId={modelId}
            versionId={curVerionId}
            onSuccess={() => {
              doQueryDetail()
              doQueryVersions()
            }}
          ></ModelerSetNewVersion>
      )
    }
  </Space>

  return <Spin spinning={loading} wrapperClassName="page-wrap">
    <DetailHeader
      title={renderHeadTitle()}
      extra={renderHeadBtns()}
    ></DetailHeader>
    <div className="page-body" style={{ padding: 20 }}>
      <Row>
        <Col span={11}>
          <UserEditableTagList
            disabled={isReleaseVersion}
            value={userIds}
            onChange={handleChangeUser}
          ></UserEditableTagList>
        </Col>
        <Col span={11} offset={2}>
          <GroupEditableTagList
            disabled={isReleaseVersion}
            value={groupIds}
            onChange={handleChangeGroup}
          ></GroupEditableTagList>
        </Col>
      </Row>
      <EditableProcessList
        value={appProcesses}
        onChange={handleChangeProcess}
        disabled={isReleaseVersion}
      ></EditableProcessList>
    </div>
  </Spin>
}

export default ModelerAppDesign